package com.crm.custinfo.controller;

import com.crm.custinfo.domain.*;
import com.crm.custinfo.service.*;
import com.crm.custinfo.service.impl.UserInfoComm;
import com.crm.suborgConfig.domain.BaseSuborgConfig;
import com.crm.suborgConfig.service.IBaseSuborgConfigService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.ConfigConstant;
import com.ruoyi.common.constant.RedisConstant;
import com.ruoyi.common.constant.StatusConstant;
import com.ruoyi.common.constant.TypeConstant;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.Md5Encrypt;
import com.ruoyi.common.utils.ObjectUtil;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.service.*;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.collections4.Predicate;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.ruoyi.common.utils.SecurityUtils.getLoginUser;


/**
 * 客户信息Controller
 *
 * @author ruoyi
 * @date 2023-12-28
 */
@RestController
@RequestMapping("/crmsys/custinfo")
public class CustInfoController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(CustInfoController.class);
    @Autowired
    private ICustInfoService custInfoService;
    @Autowired
    private UserInfoComm userInfoComm;
    @Autowired
    private ISysConfigService baseSysConfigService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private ISysDeptService isysDeptService;
    @Autowired
    private IUserAddmustDetailService userAddmustDetailService;

    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysDictDataService isysDictDataService;
    @Autowired
    private IBaseSuborgConfigService iBaseSuborgConfigService;

    @Autowired
    private ISysRoleService iroleService;
    @Autowired
    private IUserOperateRecordService iuserOperateRecordService;

    @Autowired
    private IUserOperateDetailService iuserOperateDetailService;

    @Autowired
    private ICustBlackListService custBlackListService;

    @Autowired
    private ICustInfoDelService custInfoDelService;
    @Autowired
    private ICustCommentRecordService custCommentRecordService;

    /**
     * 查询客户信息列表
     */
    @PreAuthorize("@ss.hasPermi('crmsys:custinfo:list')")
    @GetMapping("/list")
    public TableDataInfo list(CustInfo custInfo) {
        startPage();

        List<CustInfo> list = custInfoService.selectCustInfoList(custInfo);
        return getDataTable(list);
    }

    /**
     * 获取客户信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('crmsys:custinfo:query')")
    @PostMapping("/decryptMobile")
    public AjaxResult decryptMobile(@RequestBody CustInfo custInfo) {
        return custInfoService.decryptMobile(custInfo);
    }

    /**
     * 导出客户信息列表
     */
    @PreAuthorize("@ss.hasPermi('crmsys:custinfo:export')")
    @Log(title = "客户信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CustInfo custInfo) {
        List<CustInfo> list = custInfoService.selectCustInfoList(custInfo);
        ExcelUtil<CustInfo> util = new ExcelUtil<CustInfo>(CustInfo.class);
        util.exportExcel(response, list, "客户信息数据");
    }

    /**
     * 获取客户信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('crmsys:custinfo:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(custInfoService.selectCustInfoById(id));
    }

    /**
     * 新增客户信息
     */
    @PreAuthorize("@ss.hasPermi('crmsys:custinfo:add')")
    @Log(title = "客户信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CustInfo custInfo) {
        try {
            Date curDate = DateUtils.getNowDate();
            SysUser user = getLoginUser().getUser();
            SysDept sysDept = isysDeptService.selectDeptById(getLoginUser().getDeptId());
            custInfo.setApplyTime(curDate);
            custInfo.setUserId(user.getUserId());
            custInfo.setDeptId(user.getDeptId());
            custInfo.setApplyTime(new Date());
            custInfo.setStatus(StatusConstant.CUST_STATUS_FOLLOW);
            custInfo.setReDistributeStatus(StatusConstant.DISTRIBUTE_STATUS_YES);
            custInfo.setLastUpdateBy(user.getUserId());
            custInfo.setUpdateTime(curDate);
            custInfo.setLastRemarkTime(curDate);
            custInfo.setCity(sysDept.getCity());
            custInfo.setDistributeRemark(String.format("%s:手动新增%s", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, new Date()), user.getNickName()));
            CustInfo custInfo1 = new CustInfo();
            custInfo1.setMobile(custInfo.getMobile());
            List<CustInfo> infos = custInfoService.selectCustInfoList(custInfo1);

            if (CollectionUtils.isNotEmpty(infos)) {
                for (CustInfo info : infos) {
                    if (info.getUserId() != null && info.getUserId().longValue() == user.getUserId()) {
                        return AjaxResult.error(String.format("你名下已存在该客户信息，姓名[%s]",  infos.get(0).getCustName()));
                    }
                }
            }

            Map<String, Object> map = custInfo.getParams();
            String remarkNew = MapUtils.getString(map, "remarkNew", "");
            custInfo.setAddUserId(getUserId());
            custInfo.setMd5val(Md5Encrypt.md5(custInfo.getMobile()));
            custInfoService.insertCustInfo(custInfo);
            custInfo1 = new CustInfo();
            custInfo1.setAddUserId(custInfo.getAddUserId());
            custInfo1.setMd5val(custInfo.getMd5val());
            custInfo1.setUserId(custInfo.getUserId());
            infos = custInfoService.selectCustInfoList(custInfo1);
            custInfo=infos.get(0);
            if (StringUtils.isNotBlank(remarkNew)) {
                if(custInfo.getReDistributeStatus()==null) {
                    custInfo.setReDistributeStatus(StatusConstant.DISTRIBUTE_STATUS_YES);// 必须有备注才移入我的客户池
                }
                custInfo.setLastRemarkTime(curDate);

                CustCommentRecord custCommentRecord = new CustCommentRecord();
                custCommentRecord.setCustId(custInfo.getId());
                custCommentRecord.setType(4L);
                custCommentRecord.setNickName(getLoginUser().getUser().getNickName());
                custCommentRecord.setUserid(getLoginUser().getUser().getUserId());
                custCommentRecord.setRemark(remarkNew + "-K-");
                custCommentRecordService.insertCustCommentRecord(custCommentRecord);
            }
            if (StringUtils.isNotBlank(remarkNew)) {
                String oldRemark = StringUtils.defaultIfBlank(custInfo.getRemark(), "");
                if (StringUtils.isNotBlank(oldRemark) && StringUtils.isNotBlank(remarkNew)) {
                    oldRemark = "<br>" + oldRemark;
                }

                custInfo.setRemark((StringUtils.isBlank(remarkNew) ? "" :
                        remarkNew + DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, new Date())
                                + getLoginUser().getUser().getNickName()) + "-K-" + oldRemark);
            }
            custInfoService.encryptMobile(custInfo, log);
        } catch (Exception e) {
            return AjaxResult.error("新增失败");
        }
        return AjaxResult.success("新增成功");
    }

    /**
     * 修改客户信息
     */
    @PreAuthorize("@ss.hasPermi('crmsys:custinfo:edit')")
    @Log(title = "客户信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CustInfo custInfo) {

        return toAjax(custInfoService.updateCustInfo(custInfo));
    }

    /**
     * 删除客户信息
     */
    @PreAuthorize("@ss.hasPermi('crmsys:custinfo:remove')")
    @Log(title = "客户信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(custInfoService.deleteCustInfoByIds(ids));
    }

    /**
     * 公共池信息列表
     */
    @PreAuthorize("@ss.hasPermi('crmsys:custinfo:publicCustlist')")
    @GetMapping("/publicCustlist")
    public TableDataInfo publicCustlist(CustInfo custInfo) {

        LoginUser loginUser = getLoginUser();
        // 分公司总负责人级别以上能看整个城市，其他角色仅能看当前分公司或合并的分公司数据

        List<SysDept> deptList = userInfoComm.findAllOrgsUnderUser(loginUser.getUser(), "1");
        Long[] orgIds = new Long[deptList.size()];
        for (int i = 0; i < deptList.size(); i++) {
            SysDept sysDept = deptList.get(i);
            orgIds[i] = sysDept.getDeptId();
        }
        custInfo.setIsDelete("0");//未加入垃圾库
        custInfo.setDeptIds(orgIds);

        Map<String,Object> map = custInfo.getParams();
        if(custInfo.getUnfollow_day()!=null&&!"".equals(custInfo.getUnfollow_day())){
            map.put("endupdateTime", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.addDays(new Date(), -Integer.parseInt(custInfo.getUnfollow_day()))));

        }
        if (StringUtils.isNotBlank(custInfo.getFollowTimeStart())) {
            // 需要检索
            map.put("followTimeStart", custInfo.getFollowTimeStart());
        }
        if (StringUtils.isNotBlank(custInfo.getFollowTimeEnd())) {
            // 需要检索
            map.put("followTimeEnd", custInfo.getFollowTimeEnd());
        }
        custInfo.setParams(map);
        startPage();
        List<CustInfo> list = custInfoService.selectCustInfoList2(custInfo);
        return getDataTable(list);
    }

    /**
     * 手动获取客户列表
     *
     * @return
     */
    @GetMapping("/publicCustFetchlist")
    public TableDataInfo publicCustFetchlist(CustInfo custInfo) {

        Map<String, Object> resMap = new HashMap<String, Object>();
        // 当前用户
        SysUser user = getLoginUser().getUser();
        Map<String, Object> params = new HashMap<String, Object>();
        // 组装查询条件
        if (custInfo == null) {
            custInfo = new CustInfo();
        }

        //获取登录账号的角色信息
        Map<String, Object> roleMap = userInfoComm.getUserRoleCode();
        // 分公司总负责人级别以上能看整个城市，其他角色仅能看当前分公司或合并的分公司数据
        long selectOrgId = user.getDeptId();
        boolean isCompanyBoss = userInfoComm.isCompanyBoss(roleMap);
        if (isCompanyBoss) {
            selectOrgId = userInfoComm.getCurentCompanyOrgId(selectOrgId);
        } else {
            selectOrgId = userInfoComm.getCurentSubCompanyOrgId(selectOrgId);
        }
        boolean fetchConfigFlag = false;
        if (roleMap.get("company_leader").equals("1") || roleMap.get("suborg_leader").equals("1") || roleMap.get("sub_leader").equals("1")) {
            resMap.put("fetchConfigFlag", "1");
            fetchConfigFlag = true;
        } else {
            resMap.put("fetchConfigFlag", "0");
        }

        // 每人每天获取数限制
        int fetchCountLimit = baseSysConfigService.getItemValueByItemKey(ConfigConstant.PUBLIC_CUST_FETCH_LIMIT_COUNT, 30);
        // 获取数据的时间段限制
        String fetchTimeNoLimit = baseSysConfigService.getItemValueByItemKey(ConfigConstant.PUBLIC_CUST_FETCH_NOLIMIT_TIME, "12:00-14:00,17:30-18:30,20:00-09:00");
        String fetchTimeLimit = baseSysConfigService.getItemValueByItemKey(ConfigConstant.PUBLIC_CUST_FETCH_LIMIT_TIME, "09:00-12:00,14:00-17:30,18:30-20:00");

        resMap.put("fetchTimeNoLimit", fetchTimeNoLimit);
        resMap.put("fetchTimeLimit", fetchTimeLimit);
        // 检查当前系统时间是否在禁止时间内
        int[] roleType = new int[]{0, 1, 2}; // 业务员&学徒、部长、团队长
        SysDept dept = isysDeptService.selectDeptById(getLoginUser().getDeptId());
        String company_id = dept.getCompanyId();
        if ("1021".equals(company_id)) {
            // 20220928 深圳柏易融新增优化：获取客户设置把非部长一分为二，分为业务员和学徒分别设置
            roleType = new int[]{0, 1, 2, 5, 8};// 业务员&学徒、部长、团队长、业务员、学徒
        }
        for (int type : roleType) {
            Map<String, String> fetchMap = getFetchConfig(selectOrgId, type);
            String cityFetchCountLimit = MapUtils.getString(fetchMap, "fetchCountLimit"); // 城市数量上限
            String cityFetchIsOpen = MapUtils.getString(fetchMap, "fetchIsOpen", "");// 城市开关
            resMap.put("fetchCountLimit" + type, StringUtils.isNotBlank(cityFetchCountLimit) ? Integer.valueOf(cityFetchCountLimit) : fetchCountLimit);
            resMap.put("fetchIsOpen" + type, cityFetchIsOpen);
        }
        if ("1011".equals(company_id) && MapUtils.getIntValue(roleMap, "suborg_leader", 0) == 1) {
            // 上海淼批分公司负责人可24小时获取客户
            resMap.put("fetchIsOpen2", TypeConstant.FLAG_YES);
        }
        // 查询当日已获取客户数量
        resMap.put("fetchCount", userInfoComm.getUserDailyFetchDatas(getLoginUser().getUserId()));
        boolean isLimit = false;
        int isDepartLeader = MapUtils.getIntValue(roleMap, "depart_leader", 0);
        int isXuetu = MapUtils.getIntValue(roleMap, "is_xuetu", 0);
        int isEmp = MapUtils.getIntValue(roleMap, "is_emp", 0);
        int isAreaSubLeader = MapUtils.getIntValue(roleMap, "area_leader", 0);
        //
        if (!fetchConfigFlag && !isCompanyBoss) {
            boolean isLimitTime = custInfoService.checkFetchDatalimit(fetchTimeLimit);
            if (isDepartLeader == 1) {
                // 部长
                if (isLimitTime && !TypeConstant.FLAG_YES.equals(MapUtils.getString(resMap, "fetchIsOpen1"))) {
                    isLimit = true;
                }
            } else if (isAreaSubLeader >= 1) {
                // 团队长
                if (isLimitTime && !TypeConstant.FLAG_YES.equals(MapUtils.getString(resMap, "fetchIsOpen2"))) {
                    isLimit = true;
                }
            } else if ("1021".equals(company_id)) {
                if (isXuetu == 1 && isLimitTime && !TypeConstant.FLAG_YES.equals(MapUtils.getString(resMap, "fetchIsOpen8"))) {
                    isLimit = true; // 学徒
                } else if (isEmp == 1 && isLimitTime && !TypeConstant.FLAG_YES.equals(MapUtils.getString(resMap, "fetchIsOpen5"))) {
                    isLimit = true; // 业务员
                }
            } else {
                // 业务员和其他角色
                if (isLimitTime && !TypeConstant.FLAG_YES.equals(MapUtils.getString(resMap, "fetchIsOpen0"))) {
                    isLimit = true;
                }
            }
        }

        // 通用部门、顾问、分配顾问查询条件组装
        //long selectOrgId = custInfo.getOrgId() == null || custInfo.getOrgId() == -1L? -1 : custInfo.getOrgId();
        Map<Long, String> selectOrgMap = new HashMap<Long, String>();
        Map<Long, String> selectEmpMap = new HashMap<Long, String>();
        long orgId = custInfo.getOrgId() == null || custInfo.getOrgId() == -1L ? -1L : custInfo.getOrgId();

        List<SysDept> sysDepts = isysDeptService.selectChildrenAllDeptById(selectOrgId);
        Long[] orgIds = new Long[sysDepts.size()];
        for (int i = 0; i < sysDepts.size(); i++) {
            SysDept sysDept = sysDepts.get(i);
            orgIds[i] = sysDept.getDeptId();
        }
        // 判断顾问名下客户数是否已达上限
        int userCustCount = userInfoComm.getUserDailyFetchDatas(getLoginUser().getUserId());

        if (!fetchConfigFlag && !isCompanyBoss && userCustCount >= getLoginUser().getUser().getReceiveTotallimit()) {
            isLimit = true;
            resMap.put("totalCountLimit", "1");
            resMap.put("errorInfo", "当前名下客户数" + userCustCount + "，无法继续获取数据。");
        }
        if (isLimit) {
            resMap.put("errorInfo", 1);
            resMap.put("custInfo", custInfo);
            resMap.put("list", getDataTable(new ArrayList<CustInfo>()));
            return getDataTable(new ArrayList<CustInfo>());
        }


        custInfo.setIsDelete("0");//未加入垃圾库
        custInfo.setDeptIds(orgIds);


        startPage();
        List<CustInfo> list = custInfoService.selectCustInfoList2(custInfo);
        return getDataTable(list);
    }

    /**
     * 获取分配公共的参数配置
     */
    @GetMapping("/getPublicCustSet")
    public AjaxResult getPublicCustSet(CustInfo custInfo) {
        LoginUser loginUser = getLoginUser();
        // 分公司总负责人级别以上能看整个城市，其他角色仅能看当前分公司或合并的分公司数据
        long selectOrgId = loginUser.getDeptId();
        //获取登录账号的角色信息
        Map<String, Object> roleMap = userInfoComm.getUserRoleCode();
        if (roleMap.get("company_leader").equals("1") || roleMap.get("suborg_leader").equals("1") || roleMap.get("sub_leader").equals("1")) {

            roleMap.put("fetchConfigFlag", "1");
        } else {
            roleMap.put("fetchConfigFlag", "0");

        }
        // 每人每天获取数限制
        int fetchCountLimit = baseSysConfigService.getItemValueByItemKey(ConfigConstant.PUBLIC_CUST_FETCH_LIMIT_COUNT, 30);
        // 获取数据的时间段限制
        String fetchTimeNoLimit = baseSysConfigService.getItemValueByItemKey(ConfigConstant.PUBLIC_CUST_FETCH_NOLIMIT_TIME, "12:00-14:00,17:30-18:30,20:00-09:00");
        String fetchTimeLimit = baseSysConfigService.getItemValueByItemKey(ConfigConstant.PUBLIC_CUST_FETCH_LIMIT_TIME, "09:00-12:00,14:00-17:30,18:30-20:00");

        String custCanTakeBack = baseSysConfigService.getItemValueByItemKey(ConfigConstant.CUST_CAN_TAKEBACK, "0");
        // 每人每天获取数限制
        int fetCount = userInfoComm.getUserDailyFetchDatas(getLoginUser().getUserId());
        boolean isCompanyBoss = userInfoComm.isCompanyBoss(roleMap);
        if (isCompanyBoss) {
            selectOrgId = userInfoComm.getCurentCompanyOrgId(selectOrgId);
        } else {
            selectOrgId = userInfoComm.getCurentSubCompanyOrgId(selectOrgId);
        }

        // 检查当前系统时间是否在禁止时间内
        int[] roleType = new int[]{0, 1, 2}; // 业务员&学徒、部长、团队长
        SysDept dept = isysDeptService.selectDeptById(getLoginUser().getDeptId());

        String company_id = dept.getCompanyId();
        if ("1021".equals(company_id)) {
            // 20220928 深圳柏易融新增优化：获取客户设置把非部长一分为二，分为业务员和学徒分别设置
            roleType = new int[]{0, 1, 2, 5, 8};// 业务员&学徒、部长、团队长、业务员、学徒
        }
        for (int type : roleType) {
            Map<String, String> fetchMap = getFetchConfig(selectOrgId, type);
            String cityFetchCountLimit = MapUtils.getString(fetchMap, "fetchCountLimit"); // 城市数量上限
            String cityFetchIsOpen = MapUtils.getString(fetchMap, "fetchIsOpen", "");// 城市开关
            roleMap.put("fetchCountLimit" + type, StringUtils.isNotBlank(cityFetchCountLimit) ? Integer.valueOf(cityFetchCountLimit) : fetchCountLimit);
            roleMap.put("fetchIsOpen" + type, cityFetchIsOpen);
        }
        roleMap.put("fetchCountLimit", fetchTimeNoLimit);
        roleMap.put("fetchTimeLimit", fetchTimeLimit);
        roleMap.put("custCanTakeBack", custCanTakeBack);
        roleMap.put("company_id", company_id);

        roleMap.put("fetCount", fetCount);
        if ("1011".equals(company_id) && MapUtils.getIntValue(roleMap, "suborg_leader", 0) == 1) {
            // 上海淼批分公司负责人可24小时获取客户
            roleMap.put("fetchIsOpen2", TypeConstant.FLAG_YES);
        }
        return AjaxResult.success(roleMap);
    }

    /**
     * 查询数据获取配置
     *
     * @param orgId 部门id
     * @param type  设置类别 0-非部长 1-部长 2-团队长
     * @return
     */
    public Map<String, String> getFetchConfig(long orgId, int type) {
        Map<String, String> fetchMap = new HashMap<String, String>();

        try {
            String key1 = "fetchCountLimit:" + type + "_" + orgId;
            String key2 = "fetchIsOpen:" + type + "_" + orgId;
            String fetchCountLimit = redisCache.hasKey(key1) ? redisCache.getCacheObject(key1).toString() : "";
            String fetchIsOpen = redisCache.hasKey(key2) ? redisCache.getCacheObject(key2).toString() : "";
            fetchMap.put("fetchCountLimit", fetchCountLimit);
            fetchMap.put("fetchIsOpen", fetchIsOpen);
        } catch (Exception e) {
            log.error("查询数据获取设置redis操作异常", e);
        }
        return fetchMap;
    }

    @PostMapping("/setFetchConfig")
    public AjaxResult setFetchConfig(@RequestBody String params) {
        //获取登录账号的角色信息
        try {
            LoginUser loginUser = getLoginUser();
            Map<String, Object> roleMap = userInfoComm.getUserRoleCode();
            boolean fetchConfigFlag = false;
            if (roleMap.get("company_leader").equals("1") || roleMap.get("suborg_leader").equals("1") || roleMap.get("sub_leader").equals("1")) {
                fetchConfigFlag = true;
            }
            if (!fetchConfigFlag) {
                return AjaxResult.error("无操作权限");
            }
            long orgId = userInfoComm.getCurentSubCompanyOrgId(loginUser.getDeptId());
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode rootNode = objectMapper.readTree(params);

            int roleType = rootNode.get("roleType").asInt();
            String fetchIsOpen = rootNode.get("fetchIsOpen").asText();
            fetchIsOpen = "true".equals(fetchIsOpen) ? "1" : "0";
            int fetchCountLimit = rootNode.get("fetchCountLimit").asInt();

            // 20220105 公司级别角色可以设置底下所有分公司的公共池获取参数
            SysDept cityOrg = isysDeptService.selectDeptById(orgId);
            if (cityOrg != null && cityOrg.getAncestors().split(",").length <= 1) {
                logger.info("公司级别负责人{},批量设置公共池获取参数：roleType={},fetchIsOpen={},fetchCountLimit={}", loginUser.getUsername(), roleType, fetchIsOpen, fetchCountLimit);

                List<SysDept> subOrgs = isysDeptService.selectChildrenDeptById(cityOrg.getDeptId());

                for (SysDept org : subOrgs) {
                    custInfoService.setFetchConfig(org.getDeptId(), roleType, fetchCountLimit, fetchIsOpen);
                }
                custInfoService.setFetchConfig(cityOrg.getDeptId(), roleType, fetchCountLimit, fetchIsOpen);
            } else {
                logger.info("分公司级别负责人{},设置本分公司公共池获取参数：roleType={},fetchIsOpen={},fetchCountLimit={}", loginUser.getUsername(), roleType, fetchIsOpen, fetchCountLimit);
                custInfoService.setFetchConfig(orgId, roleType, fetchCountLimit, fetchIsOpen);
            }

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return AjaxResult.error("程序错误");

        }
        return AjaxResult.success("设置成功");
    }

    /**
     * 获取客户加入我的再分配客户池
     *
     * @return
     */

    @PostMapping("/fetchCustToMyReCust/{ids}")
    public AjaxResult fetchCustToMyReCust(@PathVariable Long[] ids) {
        try {

            LoginUser loginUser = getLoginUser();

            long selectOrgId = userInfoComm.getCurentSubCompanyOrgId(loginUser.getDeptId());

            Map<String, Object> roleMap = userInfoComm.getUserRoleCode();
            boolean fetchConfigFlag = false;
            if (roleMap.get("company_leader").equals("1")) {
                fetchConfigFlag = true;
            }

            int isDepartLeader = MapUtils.getIntValue(roleMap, "depart_leader", 0);
            int isXuetu = MapUtils.getIntValue(roleMap, "is_xuetu", 0);
            int isEmp = MapUtils.getIntValue(roleMap, "is_emp", 0);
            int type = isDepartLeader == 1 ? 1 : 0;


            SysDept dept = isysDeptService.selectDeptById(getLoginUser().getDeptId());
            String company_id = dept.getCompanyId();
            if ("1021".equals(company_id)) {
                // 20220928 深圳柏易融新增优化：获取客户设置把非部长一分为二，分为业务员和学徒分别设置
                type = isXuetu == 1 ? 8 : (isEmp == 1 ? 5 : isDepartLeader == 1 ? 1 : 0);
            }
            Map<String, String> fetchMap = getFetchConfig(selectOrgId, type);
            String cityFetchCountLimit = MapUtils.getString(fetchMap, "fetchCountLimit"); // 城市数量上限
            String cityFetchIsOpen = MapUtils.getString(fetchMap, "fetchIsOpen", "");// 城市开关
            // 分公司负责人和团队长共用配置type=2
            if (MapUtils.getIntValue(roleMap, "area_leader", 0) == 1 || MapUtils.getIntValue(roleMap, "suborg_leader", 0) == 1) {
                //cityFetchCountLimit = baseSysConfigService.getItemValueByItemKey(ConfigConstant.PUBLIC_CUST_FETCH_AREALEADER_LIMIT_COUNT, "200"); //团队长默认200
                Map<String, String> fetchMap2 = getFetchConfig(selectOrgId, 2);
                cityFetchCountLimit = MapUtils.getString(fetchMap2, "fetchCountLimit"); // 城市数量上限
                cityFetchIsOpen = MapUtils.getString(fetchMap2, "fetchIsOpen", "");// 城市开关
            }
            int fetchCountLimit = baseSysConfigService.getItemValueByItemKey(ConfigConstant.PUBLIC_CUST_FETCH_LIMIT_COUNT, 30);
            fetchCountLimit = StringUtils.isNotBlank(cityFetchCountLimit) ? Integer.valueOf(cityFetchCountLimit) : fetchCountLimit;
            String fetchTimeLimit = baseSysConfigService.getItemValueByItemKey(ConfigConstant.PUBLIC_CUST_FETCH_LIMIT_TIME, "09:00-12:00,14:00-17:30,18:30-20:00");
            if ("1011".equals(company_id) && MapUtils.getIntValue(roleMap, "suborg_leader", 0) == 1) {
                // 上海淼批分公司负责人可24小时获取客户
                cityFetchIsOpen = TypeConstant.FLAG_YES;
            }
            // 检查当前系统时间是否在禁止时间内 （开关已打开，不校验）
            if (StringUtils.isBlank(cityFetchIsOpen) && custInfoService.checkFetchDatalimit(fetchTimeLimit)) {

                return AjaxResult.error("已过业务时间");
            }
            // 检查数据获取功能是否开启
            if (TypeConstant.FLAG_NO.equals(cityFetchIsOpen)) {
                return AjaxResult.error("数据获取功能已关闭");
            }


            if (ids.length < 1) {
                return AjaxResult.error("请选择一条记录");
            }
            // 单次获取条数限制
            int selectCountLimit = baseSysConfigService.getItemValueByItemKey(ConfigConstant.PUBLIC_CUST_FETCH_SELECT_LIMIT, 10);
            List<SysUser> list = new ArrayList<SysUser>();
            int successCount = 0;
            int selectCount = 0;
            String succCustIds = "";
            for (Long id : ids) {
                if (selectCount >= selectCountLimit) {
                    break;
                }
                CustInfo c = custInfoService.selectCustInfoById(id);
                if (c == null) {
                    continue;
                }
                // 20220425新增个性化：1018-北京星速、1031-北京旭晟荐介客户不可被获取
                if (("1018".equals(company_id) || "1031".equals(company_id)) && TypeConstant.STAR_LEVEL_6.equals(c.getStarLevel())) {
                    continue;
                }
                Long custEmpId = c.getEmpId();
                if (custEmpId != null && custEmpId.longValue() != loginUser.getUserId()) {
                    logger.info(String.format("客户数据获取：客户id=%s,name=%s,当前所在顾问id=%s,当前顾问%s获取该客户失败", c.getId(), c.getCustName(), custEmpId, loginUser.getUserId()));
                    continue;
                }
                // 每人每天获取数限制
                int fetCount = userInfoComm.getUserDailyFetchDatas(loginUser.getUserId());
                if (!fetchConfigFlag && (fetCount + successCount >= fetchCountLimit)) {
                    break;
                }
                c.setUserId(loginUser.getUserId());
                c.setDeptId(loginUser.getDeptId());
                c.setReDistributeStatus(StatusConstant.DISTRIBUTE_STATUS_RE);// 再分配标识
                c.setReDistributeTime(new Date()); // 再分配时间
                //c.setDistributeTime(new Date());
                StringBuffer distsb = new StringBuffer();
                distsb.append(StringUtils.defaultIfBlank(c.getDistributeRemark(), "")).append("<br>").append(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, new Date()))
                        .append(getLoginUser().getUser().getNickName()).append("从公共池手动获取数据").append("-K-");
                c.setDistributeRemark(distsb.toString());
                c.setUpdateTime(new Date());
                custInfoService.updateCustInfo(c);
                successCount++;

                succCustIds += id + ",";
                selectCount++;
            }
            if (succCustIds.endsWith(",")) {
                succCustIds = succCustIds.substring(0, succCustIds.length() - 1);
            }
            if (StringUtils.isNotBlank(succCustIds)) {
                UserAddmustDetail detail = new UserAddmustDetail();
                detail.setOperType("4");
                detail.setOperDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, new Date()));
                detail.setEmpId(loginUser.getUserId());
                List<UserAddmustDetail> details = userAddmustDetailService.selectUserAddmustDetailList(detail);
                if (CollectionUtils.isEmpty(details)) {
                    // 生成从公共池获取客户的记录
                    UserAddmustDetail must = new UserAddmustDetail();
                    must.setEmpId(loginUser.getUserId());
                    must.setCustIds(succCustIds);
                    must.setOperType("4");
                    must.setOperDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, new Date()));
                    must.setCreateTime(new Date());
                    userAddmustDetailService.insertUserAddmustDetail(must);
                    logger.info(String.format("顾问[%s]本次从公共池获取成功客户[%s], 新增获取记录", loginUser.getUserId(), succCustIds));
                } else {
                    UserAddmustDetail must = details.get(0);
                    String oldCustIds = must.getCustIds();
                    String newCustIds = oldCustIds + "," + succCustIds;
                    must.setCustIds(newCustIds);
                    userAddmustDetailService.updateUserAddmustDetail(must);
                    logger.info(String.format("顾问[%s]本次从公共池获取成功客户[%s], 更新获取记录，更新前[%s]，更新后[%s]", loginUser.getUserId(), succCustIds, oldCustIds, must.getCustIds()));
                }
            }
            return AjaxResult.success(String.format("本次选择数据%s条,成功获取%s条,获取失败%s条", ids.length, successCount, ids.length - successCount));
        } catch (NumberFormatException e) {
            return AjaxResult.error("分配错误");
        }
    }

    /**
     * 我的客户信息列表页 & 再分配客户信息列表 & 当日必跟进客户
     *
     * @param custInfo
     * @return
     */
    @PreAuthorize("@ss.hasPermi('crmsys:myCustinfo:list')")
    @GetMapping("/getMyCustlist")
    public AjaxResult getMyCustlist(CustInfo custInfo) {
        Map<String, Object> resMap = new HashMap<String, Object>();
        try {
            LoginUser loginUser = getLoginUser();
            Map<String, Object> params = new HashMap<String, Object>();
            // 组装查询条件
            if (custInfo == null) {
                custInfo = new CustInfo();
            }
            // 分公司总负责人级别以上能看整个城市，其他角色仅能看分公司级别
            Map<String, Object> roleMap = userInfoComm.getUserRoleCode();
            // 计算数量
//            Map<String, Object> resMapCount = custInfoService.unfollowMorethandays("1", roleMap);
//            resMap.put("resMapCount", resMapCount);
            resMap.put("resMapCount", new HashMap<>());
            resMap.put("roleMap", roleMap);
            long orgId = loginUser.getDeptId();
            long userid = loginUser.getUserId();
            boolean isCompanyBoss = userInfoComm.isCompanyBoss(roleMap);
            if (isCompanyBoss) {
                orgId = userInfoComm.getCurentCompanyOrgId(orgId);
            } else {
                orgId = userInfoComm.getCurentSubCompanyOrgId(orgId);
            }
            String custOpType = MapUtils.getString(custInfo.getParams(), "custOpType");//参数获取

            if ("mycust".equals(custOpType)) { // 我的客户
                custInfo.setUserId(userid);
//                custInfo.setDeptId(loginUser.getDeptId());
                custInfo.setReDistributeStatus(StatusConstant.DISTRIBUTE_STATUS_YES);
            } else if ("recust".equals(custOpType)) {
                custInfo.setUserId(userid);
                custInfo.setReDistributeStatus(StatusConstant.DISTRIBUTE_STATUS_RE);// 再分配客户
            } else if ("must".equals(custOpType)) {
                custInfo.setUserId(userid);
                custInfo.setReDistributeStatus(StatusConstant.DISTRIBUTE_STATUS_MUST);// 必跟进客户
            } else if ("select".equals(custOpType)) { // 检索整个库
                //custInfo.setEmpId(user.getEmpId());
                //custInfo.setReDistributeStatus(StatusConstant.DISTRIBUTE_STATUS_YES);
            } else if ("select1".equals(custOpType)) { // 检索关联客户
                //custInfo.setEmpId(user.getEmpId());
                //custInfo.setReDistributeStatus(StatusConstant.DISTRIBUTE_STATUS_YES);
            } else if ("select2".equals(custOpType)) { // 检索整个库
                //custInfo.setReDistributeStatus(StatusConstant.DISTRIBUTE_STATUS_YES);
//                resMap.put("type", getStrParameter("type", ""));
            }
            if (StringUtils.isNotBlank(custInfo.getCustName())) {
                custInfo.setCustName(URLDecoder.decode(custInfo.getCustName(), "UTF-8"));
            }

            custInfo.setIsDelete("0");//未加入垃圾库
//
//            if (custOpType.startsWith("select")) {
//
//                if (isCompanyBoss) {
//                    params.put("orgIds", getOrgIdsUnderOrg(orgId));
//                } else {
//                    params.put("orgIds", getCurentSubOrgIds(orgId));
//                }
//            }


/** 前端处理

 //            String unfollow_day = getStrParameter("unfollow_day", "");
 //            if (StringUtils.isNotBlank(unfollow_day) && NumberUtils.isNumber(unfollow_day)) {
 //                // 通过未跟进超过几天查询的时候，查询结果集中剔除荐介客户
 //                params.put("starLevelNoEqual", TypeConstant.STAR_LEVEL_6);
 //            }
 //            // 20200703若系统状态是3，则客户列表仅显示10（配置）天内的数据,且不包括扫码数据
 //            if ("3".equals(user.getSysStatus())) {
 //                int days = baseSysConfigService.getItemValueByItemKey(ConfigConstant.SYS_CUST_DATA_BEFORE_DAYS, 10);
 //                params.put("applyTimeStart", DateUtil.format(DateUtil.addDay(new Date(), -days), DateUtil.DATE_TIME_FORMAT));
 //                params.put("starLevelNoEqual", TypeConstant.STAR_LEVEL_6);
 //            }
 */

            String islink = "";
            String statusin = "";
            String reStatus = "";

//            String islink = getStrParameter("islink", "");
//            String statusin = getStrParameter("statusin", "");
//            String reStatus = getStrParameter("reStatus", "");
//

            //String starLevelIn = getStrParameter("starLevelIn", "0,1,2,3,4,5,7");
            if (StringUtils.isNotBlank(islink)) { // 从快捷连接过来的
                params.put("statusin", statusin); // 带了状态则传状态
                params.put("reDistributeStatusIn", reStatus); // 再分配状态
                params.put("reDistributeStatus", "");
                params.put("fetchFlag", "0");// 已开启自动抓取
                params.put("isDelete", TypeConstant.FLAG_NO);
                params.put("starLevelNoEqual", TypeConstant.STAR_LEVEL_6);
                params.put("channelNoEqual", TypeConstant.CHL_QRCODE);

//                custInfo.setStatus(statusin);
//                custInfo.setReDistributeStatus(reStatus);
//                custInfo.setReDistributeStatus(reStatus);
            }

            if(custInfo.getUnfollow_day()!=null&&!"".equals(custInfo.getUnfollow_day())){
                Map<String,Object> map = custInfo.getParams();
                map.put("endupdateTime", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.addDays(new Date(), -Integer.parseInt(custInfo.getUnfollow_day()))));
                custInfo.setParams(map);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return AjaxResult.error("获取数据异常");

        }
        startPage();

        List<CustInfo> list = custInfoService.selectCustInfoList(custInfo);
        resMap.put("list", getDataTable(list));
        return AjaxResult.success(resMap);
    }

    /**
     * 我的客户信息列表页 & 再分配客户信息列表 & 当日必跟进客户
     *
     * @param custInfo
     * @return
     */
    @GetMapping("/getMyCustInfo")
    public AjaxResult getMyCustInfo(CustInfo custInfo) {
        Map<String, Object> resMap = new HashMap<String, Object>();
        try {
            LoginUser loginUser = getLoginUser();
            Map<String, Object> params = new HashMap<String, Object>();
            // 组装查询条件
            if (custInfo == null) {
                custInfo = new CustInfo();
            }
            // 分公司总负责人级别以上能看整个城市，其他角色仅能看分公司级别
            Map<String, Object> roleMap = userInfoComm.getUserRoleCode();
            // 计算数量
            Map<String, Object> resMapCount = custInfoService.unfollowMorethandays("1", roleMap);
            resMap.put("resMapCount", resMapCount);

            resMap.put("roleMap", roleMap);
            long orgId = loginUser.getDeptId();
            long userid = loginUser.getUserId();
            boolean isCompanyBoss = userInfoComm.isCompanyBoss(roleMap);
            if (isCompanyBoss) {
                orgId = userInfoComm.getCurentCompanyOrgId(orgId);
            } else {
                orgId = userInfoComm.getCurentSubCompanyOrgId(orgId);
            }
            String custOpType = MapUtils.getString(custInfo.getParams(), "custOpType");//参数获取

            if ("mycust".equals(custOpType)) { // 我的客户
                custInfo.setUserId(userid);
//                custInfo.setDeptId(loginUser.getDeptId());
                custInfo.setReDistributeStatus(StatusConstant.DISTRIBUTE_STATUS_YES);
            } else if ("recust".equals(custOpType)) {
                custInfo.setUserId(userid);
                custInfo.setReDistributeStatus(StatusConstant.DISTRIBUTE_STATUS_RE);// 再分配客户
            } else if ("must".equals(custOpType)) {
                custInfo.setUserId(userid);
                custInfo.setReDistributeStatus(StatusConstant.DISTRIBUTE_STATUS_MUST);// 必跟进客户
            }
            if (StringUtils.isNotBlank(custInfo.getCustName())) {
                custInfo.setCustName(URLDecoder.decode(custInfo.getCustName(), "UTF-8"));
            }

            custInfo.setIsDelete("0");//未加入垃圾库

            String islink = "";
            String statusin = "";
            String reStatus = "";
            if (StringUtils.isNotBlank(islink)) { // 从快捷连接过来的
                params.put("statusin", statusin); // 带了状态则传状态
                params.put("reDistributeStatusIn", reStatus); // 再分配状态
                params.put("reDistributeStatus", "");
                params.put("fetchFlag", "0");// 已开启自动抓取
                params.put("isDelete", TypeConstant.FLAG_NO);
                params.put("starLevelNoEqual", TypeConstant.STAR_LEVEL_6);
                params.put("channelNoEqual", TypeConstant.CHL_QRCODE);
            }
            if(custInfo.getUnfollow_day()!=null&&!"".equals(custInfo.getUnfollow_day())){
                Map<String,Object> map = custInfo.getParams();
                map.put("endupdateTime", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.addDays(new Date(), -Integer.parseInt(custInfo.getUnfollow_day()))));
                custInfo.setParams(map);
            }

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return AjaxResult.error("获取数据异常");

        }

        CustInfo custInfo1 = custInfoService.selectCustInfo(custInfo);
        return AjaxResult.success(custInfo1);
    }

    /**
     * 设置本人数据接收功能  1-打开 0-关闭
     *
     * @return
     */
    @PostMapping("/setReceiveNewDataFlag/{status}")
    public AjaxResult setReceiveNewDataFlag(@PathVariable String status) {
        try {
            SysUser user = getLoginUser().getUser();
            if (StringUtils.isBlank(status) || !"1,0".contains(status)) {
                return AjaxResult.error("入参有误");
            }
            if (("1".equals(status) && !"1".equals(user.getSelfReceiveFlag()))
                    || ("0".equals(status) && !"1".equals(user.getSelfCloseFlag()))) {
                return AjaxResult.error("无操作权限，请及时刷新页面");
            }
            logger.info(String.format("设置本人数据接收功能:操作人[%s]，设置标识[%s]", user.getUserId(), status));
            if ("1".equals(status)) {
                // 自助打开时判断是否强制关闭
                if (TypeConstant.FLAG_YES.equals(user.getIsForceClose())) {
                    return AjaxResult.error("数据已强制关闭，无法自助接收，请联系负责人！");
                }
            }
            user.setReceiveNew(status);
            user.setSelfReceiveStatus(status);
            userService.updateUser2(user);
        } catch (Exception e) {
            logger.error("设置本人数据接收功能异常", e);

            return AjaxResult.error("操作异常");
        }
        return AjaxResult.success("设置成功");
    }

    /**
     * 设置本人数据接收功能  1-打开 0-关闭
     *
     * @return
     */
    @PostMapping("/batchUpdateToMust/{ids}")
    public AjaxResult batchUpdateToMust(@PathVariable Long[] ids) {
        try {
            SysUser user = getLoginUser().getUser();

            if (ids.length < 1) {
                return AjaxResult.error("请选择需要操作的记录");
            }
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("ids", ids);
            CustInfo custInfo = new CustInfo();
            custInfo.setParams(params);
            List<CustInfo> list = custInfoService.selectCustInfoList(custInfo);
            for (CustInfo c : list) {
                if (c.getLockFlag() != 0 && (c.getEmpId() != null && c.getEmpId().longValue() != user.getUserId().longValue())) {
                    list.remove(c);
                }
            }

            if (list.size() < 1) {
                return AjaxResult.error("被锁定客户不可操作");
            }


            StringBuffer distsb = new StringBuffer();
            List<String> selectIds = new ArrayList<String>();
            for (CustInfo c : list) {
                c.setUpdateTime(new Date());
                c.setReDistributeStatus(StatusConstant.DISTRIBUTE_STATUS_MUST); // 标识必跟进
                distsb = new StringBuffer();
                distsb.append(StringUtils.defaultIfBlank(c.getDistributeRemark(), "")).append("<br>")
                        .append(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, new Date()))
                        .append(user.getNickName())
                        .append("把客户加入必跟进池").append("-K-");
                c.setDistributeRemark(distsb.toString());
                c.setLockFlag(0L);// 标识解锁
                selectIds.add(c.getId().toString());
                custInfoService.updateCustInfo(c);
            }


            // 生成加入必跟进池的记录
            UserAddmustDetail must = new UserAddmustDetail();
            must.setEmpId(user.getUserId());
            must.setCustIds(String.join(",", selectIds));
            must.setOperType("1");
            must.setOperDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, new Date()));
            must.setCreateTime(new Date());
            userAddmustDetailService.insertUserAddmustDetail(must);
        } catch (Exception e) {
            logger.error("加入必跟进池操作异常", e);
            return AjaxResult.error("加入必跟进池操作异常");
        }
        return AjaxResult.success("加入必跟进池成功");
    }
    /**
     * 加入我的客户
     *
     * @return
     */
    @PostMapping("/batchUpdateToMy/{ids}")
    public AjaxResult batchUpdateToMy(@PathVariable Long[] ids) {
        try {
            SysUser user = getLoginUser().getUser();

            if (ids.length < 1) {
                return AjaxResult.error("请选择需要操作的记录");
            }
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("ids", ids);
            CustInfo custInfo = new CustInfo();
            custInfo.setParams(params);
            List<CustInfo> list = custInfoService.selectCustInfoList(custInfo);
            for (CustInfo c : list) {
                if (c.getLockFlag() != 0 && (c.getEmpId() != null && c.getEmpId().longValue() != user.getUserId().longValue())) {
                    list.remove(c);
                }
            }

            if (list.size() < 1) {
                return AjaxResult.error("被锁定客户不可操作");
            }


            StringBuffer distsb = new StringBuffer();
            List<String> selectIds = new ArrayList<String>();
            for (CustInfo c : list) {
                c.setUpdateTime(new Date());
                c.setReDistributeStatus(StatusConstant.DISTRIBUTE_STATUS_YES); // 标识我的客户
                distsb = new StringBuffer();
                distsb.append(StringUtils.defaultIfBlank(c.getDistributeRemark(), "")).append("<br>")
                        .append(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, new Date()))
                        .append(user.getNickName())
                        .append("把客户加入我的客户").append("-K-");
                c.setDistributeRemark(distsb.toString());
                c.setLockFlag(0L);// 标识解锁
                selectIds.add(c.getId().toString());
                custInfoService.updateCustInfo(c);
            }
            // 生成加入我的客户的记录
            UserAddmustDetail must = new UserAddmustDetail();
            must.setEmpId(user.getUserId());
            must.setCustIds(String.join(",", selectIds));
            must.setOperType("4");
            must.setOperDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, new Date()));
            must.setCreateTime(new Date());
            userAddmustDetailService.insertUserAddmustDetail(must);

        } catch (Exception e) {
            logger.error("加入我的客户操作异常", e);
            return AjaxResult.error("加入我的客户异常");
        }
        return AjaxResult.success("加入我的客户成功");
    }
    /**
     * 加入公共池
     *
     * @return
     */
    @PostMapping("/batchUpdateToPublic/{ids}")
    public AjaxResult batchUpdateToPublic(@PathVariable Long[] ids) {
        try {
            SysUser user = getLoginUser().getUser();
            SysDept dept = isysDeptService.selectDeptById(getLoginUser().getDeptId());
            HashMap<String, Object> params = new HashMap<String, Object>();
            String company_id = dept.getCompanyId();
            params.put("company_id", company_id);
            params.put("ids", ids);

            CustInfo custInfo = new CustInfo();
            custInfo.setParams(params);
            List<SysDept> deptList = userInfoComm.getOrgListUnderOrgId(user.getDeptId());
            // 仅能处理当前用户有部门管辖权限的数据
            Long[] orgIds = new Long[deptList.size()];
            for (int i = 0; i < deptList.size(); i++) {
                SysDept sysDept = deptList.get(i);
                orgIds[i] = sysDept.getDeptId();
            }
            custInfo.setDeptIds(orgIds);

            List<CustInfo> custInfos = custInfoService.selectCustInfoList(custInfo);
            List<Long> selectIds2 = new ArrayList<Long>();

            // 荐介客户不可加入公共池，20210408新增：已锁定状态非本人不可以加入公共池
            for (CustInfo c : custInfos) {
                if ("1018".equals(company_id) || "1031".equals(company_id)) {
                    // 20220416新增个性化：1018-北京星速荐介客户可以加入公共池
                    if ((c.getLockFlag() == 0 || (c.getEmpId() != null && c.getEmpId().longValue() == user.getUserId().longValue()))
                            && !TypeConstant.CHL_QRCODE.equals(c.getChannelSource())) {
                        selectIds2.add(c.getId());
                    }
                } else {
                    if ((c.getStarLevel() == null || !TypeConstant.STAR_LEVEL_6.equals(c.getStarLevel()))
                            && (c.getLockFlag() == 0 || (c.getEmpId() != null && c.getEmpId().longValue() == user.getUserId().longValue()))
                            && !TypeConstant.CHL_QRCODE.equals(c.getChannelSource())) {
                        selectIds2.add(c.getId());
                    }
                }
            }
            if (selectIds2.isEmpty()) {
                return AjaxResult.warn("荐介客户、二维码客户和被锁定客户和其他指定客户不可操作");
            }

            Long[] ids2 = selectIds2.stream().toArray(Long[]::new);
            custInfoService.batchUpdateToPublic(ids2);
            params.put("ids", ids2);
            custInfo.setParams(params);

            custInfos = custInfoService.selectCustInfoList(custInfo);
            // 更新分配记录
            StringBuffer distsb = null;
            for (CustInfo info : custInfos) {
                distsb = new StringBuffer();
                distsb.append(StringUtils.defaultIfBlank(info.getDistributeRemark(), "")).append("<br>")
                        .append(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, new Date()))
                        .append(user.getNickName())
                        .append("回收至公共池").append("-K-");
                info.setDistributeRemark(distsb.toString());
                custInfoService.updateCustInfo(info);
            }
            logger.info(String.format("本次成功加入公共池的客户[%s]", selectIds2));
            // 生成加入公共池的记录
            UserAddmustDetail must = new UserAddmustDetail();
            must.setEmpId(user.getUserId());
            must.setCustIds(Arrays.toString(ids2));
            must.setOperType("2");
            must.setOperDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, new Date()));
            must.setCreateTime(new Date());
            userAddmustDetailService.updateUserAddmustDetail(must);

        } catch (Exception e) {
            logger.error("加入公共池操作异常", e);
            return AjaxResult.error("加入公共池操作异常");
        }
        return AjaxResult.success("加入公共池成功");
    }

    /**
     * 加入垃圾库
     *
     * @return
     */
    @PostMapping("/batchRemoveToRefusePool/{ids}")
    public AjaxResult batchRemoveToRefusePool(@PathVariable Long[] ids) {
        try {
            SysUser user = getLoginUser().getUser();

            if (ids.length < 1) {
                return AjaxResult.error("请选择需要操作的记录");
            }

            SysDept dept = isysDeptService.selectDeptById(getLoginUser().getDeptId());
            List<SysRole> sysRoles = getLoginUser().getUser().getRoles();
            String company_id = dept.getCompanyId();

            Map<String, Object> params = new HashMap<String, Object>();
            params.put("ids", ids);
            params.put("company_id", company_id);
            CustInfo custInfo = new CustInfo();
            custInfo.setParams(params);
            List<CustInfo> list = custInfoService.selectCustInfoList(custInfo);
            CollectionUtils.filter(list, new Predicate() {
                @Override
                public boolean evaluate(Object object) {
                    CustInfo bsu = (CustInfo) object;
                    return !TypeConstant.STAR_LEVEL_6.equals(bsu.getStarLevel()) && (
                            bsu.getLockFlag() == 0 || (bsu.getEmpId() != null && bsu.getEmpId().longValue() != user.getUserId().longValue()));
                }
            });

            if (list.size() < 1) {
                return AjaxResult.error("荐介客户和被锁定客户和其他指定客户不可操作");
            }
            Boolean isNeedToMiddle = false;
            for (SysRole sysRole : sysRoles) {
                if (TypeConstant.ROLE_ID_4.equals(sysRole.getRoleKey()) || TypeConstant.ROLE_ID_5.equals(sysRole.getRoleKey()) || TypeConstant.ROLE_ID_6.equals(sysRole.getRoleKey())) {
                    isNeedToMiddle = true;
                    break;
                }
            }
            String selectIds2 = "";
            StringBuffer distsb = null;
            for (CustInfo info : list) {
                distsb = new StringBuffer();
                distsb.append(StringUtils.defaultIfBlank(info.getDistributeRemark(), "")).append("<br>")
                        .append(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, new Date()))
                        .append(user.getNickName())
                        .append("加入垃圾库").append("-K-");
                info.setDistributeRemark(distsb.toString());
                info.setUpdateTime(new Date());
                if (isNeedToMiddle) {
                    info.setIsDelete(TypeConstant.FLAG_YES_2);// 加入垃圾库中间状态
                } else {
                    info.setIsDelete(TypeConstant.FLAG_YES);// 加入垃圾库
                }
                info.setLockFlag(0L);// 标识解锁
                custInfoService.updateCustInfo(info);
                selectIds2 += selectIds2 + ",";
            }
            logger.info("本次加入了垃圾库的客户ids = " + ids.toString());

            selectIds2 = selectIds2.substring(0, selectIds2.length() - 1);
            // 生成加入垃圾库的记录
            UserAddmustDetail must = new UserAddmustDetail();
            must.setEmpId(user.getUserId());
            must.setCustIds(selectIds2);
            must.setOperType("3");
            must.setOperDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, new Date()));
            must.setCreateTime(new Date());
            userAddmustDetailService.updateUserAddmustDetail(must);
        } catch (Exception e) {
            logger.error("加入垃圾库操作异常", e);
            return AjaxResult.error("加入垃圾库操作异常");
        }
        return AjaxResult.success("加入垃圾库成功");
    }

    /**
     * 回收原始分配到分公司负责人名下
     *
     * @return
     */
    @PostMapping("/batchCustTakeBack/{ids}")
    public AjaxResult batchCustTakeBack(@PathVariable Long[] ids) {
        Map<String, Object> resMap = new HashMap<String, Object>();
        try {
            SysUser user = getLoginUser().getUser();
            SysDept dept = user.getDept();
            String companyId = dept.getCompanyId();
            String leve = dept.getLevel(); //总公司 1 分公司 2 区 3 部门 4

            Map<String, Object> params = new HashMap<String, Object>();
            params.put("ids", ids);
            CustInfo custInfo = new CustInfo();
            custInfo.setParams(params);
            List<CustInfo> list = custInfoService.selectCustInfoList(custInfo);
            List<Long> custIds = new ArrayList<>();
            for (CustInfo c : list) {
                if (c.getOldEmpId() == null || c.getOldEmpId().intValue() <= 0) {
                    // 非原始分配数据
                    continue;
                }
                String odtMonth = DateUtils.parseDateToStr(DateUtils.YYYYMM, c.getOldDistributeTime());
                if (c.getOldDistributeTime() == null || !odtMonth.equals(DateUtils.getLastNMonth(0))) {
                    // 非本月数据
                    continue;
                }
                custIds.add(c.getId());
            }
            int succeed = 0;
            if (!custIds.isEmpty()) {
                // 查询分公司负责人用户
                Map<String, Object> uMap = new HashMap<>();
                uMap.put("roleIds", TypeConstant.ROLE_ID_98);
                uMap.put("isDelete", TypeConstant.FLAG_NO);

                custInfo = new CustInfo();
                params = new HashMap<String, Object>();
                params.put("ids", custIds.toArray());
                custInfo.setParams(params);


                List<CustInfo> todolist = custInfoService.selectCustInfoList(custInfo);
                for (CustInfo info : todolist) {
                    //确认用户是属于那个分公司的
                    SysUser leaderUser = new SysUser();
                    SysDept sysDept = new SysDept();
                    SysUser isUser = userService.selectUserById(info.getOldEmpId());
                    SysDept isDept = isysDeptService.selectDeptById(isUser.getDeptId());
                    sysDept.setCompanyId(isDept.getCompanyId());
                    sysDept.setLevel("2");//查找分公司
                    List<SysDept> deptList = isysDeptService.selectDeptList(sysDept);
//                    Long[] deptIds=new Long[deptList.size()];
                    List<Long> deptIds = new ArrayList();
                    for (SysDept sysDept1 : deptList) {
                        deptIds.add(sysDept1.getDeptId());
                    }
                    Map<String, Object> inParams = new HashMap<String, Object>();
                    inParams.put("orgIds", deptIds.toArray());
                    inParams.put("roleKey", TypeConstant.ROLE_ID_98);
                    SysUser inUser = new SysUser();
                    inUser.setParams(inParams);
                    List<SysUser> companyUser = userService.selectUserByDeptids(inUser);
                    if (companyUser.isEmpty()) {
                        continue;//未指派分公司负责人
                    }
                    leaderUser = userService.selectUserById(companyUser.get(0).getUserId());

                    if (!info.getOldEmpId().equals(leaderUser.getUserId())) {
                        StringBuffer distsb = new StringBuffer();
                        distsb.append(info.getDistributeRemark()).append("<br>").append(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, new Date()))
                                .append(user.getNickName())
                                .append("手动从用户").append(info.getOldEmpId().intValue()).append("回收并分配到分公司负责人名下").append("-K-");
                        info.setOldEmpId(leaderUser.getUserId());
                        info.setUserId(leaderUser.getUserId());
                        info.setDeptId(leaderUser.getUserId());
                        info.setUpdateTime(new Date());
                        info.setReDistributeStatus(StatusConstant.DISTRIBUTE_STATUS_YES);
                        info.setDistributeTime(new Date());
                        info.setDistributeRemark(distsb.toString());
                        info.setIsDelete(TypeConstant.FLAG_NO);
                        custInfoService.updateCustInfo(info);
                        succeed++;
                    }
                }
            } else {
                logger.info(String.format("本次选择回收原始分配到分公司负责人名下的客户[%s],均不满足回收条件", Arrays.toString(ids)));
            }
            return AjaxResult.success(String.format("所选客户数%s,成功回收%s", list.size(), succeed));

        } catch (Exception e) {
            logger.error("回收原始分配到分公司负责人名下操作异常", e);
            return AjaxResult.error("回收原始分配到分公司负责人名下操作异常");
        }

    }

    /**
     * 回收至待分配
     *
     * @return
     */
    @PostMapping("/batchToBeAllocated/{ids}")
    public AjaxResult batchToBeAllocated(@PathVariable Long[] ids) {
        Map<String, Object> resMap = new HashMap<String, Object>();
        try {
            SysUser user = getLoginUser().getUser();
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("ids", ids);
            CustInfo custInfo = new CustInfo();
            custInfo.setParams(params);
            List<CustInfo> list = custInfoService.selectCustInfoList(custInfo);

            List<Long> custIds = new ArrayList<Long>();

            for (CustInfo c : list) {
                if (!StatusConstant.CUST_STATUS_UNACCEPT.equals(c.getStatus())) {
                    continue;
                }
                if (c.getOldDistributeTime() == null || new Date().after(DateUtils.addHour(c.getOldDistributeTime(), 24))) {
                    continue;
                }
                if (c.getLockFlag() == 1) { //已锁定的不允许操作
                    continue;
                }
                // 二维码申请客户不允许回收
                if (StringUtils.isNotBlank(c.getChannelSource()) && TypeConstant.CHL_QRCODE.equals(c.getChannelSource())) {
                    continue;
                }
                custIds.add(c.getId());
            }
            if (!custIds.isEmpty()) {
                logger.info(String.format("本次选择回收到待分配池的客户[%s],实际待回收客户[%s]", Arrays.toString(ids), custIds));
                StringBuffer distsb = new StringBuffer();
                distsb.append(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, new Date()))
                        .append(user.getNickName())
                        .append("手动回收客户到待分配列表").append("-K-");
                params = new HashMap<String, Object>();
                params.put("ids", ids);
                params.put("disRemark", distsb.toString());
                custInfo = new CustInfo();
                custInfo.setParams(params);

                custInfoService.batchToBeAllocated(custInfo);
            } else {
                logger.info(String.format("本次选择回收到待分配池的客户[%s],均不满足回收条件", Arrays.toString(ids)));
            }
            return AjaxResult.success(String.format("所选客户数%s,成功回收%s", list.size(), custIds.isEmpty() ? 0 : custIds.size()));

        } catch (Exception e) {
            logger.error("客户回收至待分配操作异常", e);
            return AjaxResult.error("客户回收至待分配操作异常");
        }
    }

    /**
     * 待分配客户查询列表
     *
     * @return
     */
    @PreAuthorize("@ss.hasPermi('crmsys:unDistriCustlist:list')")
    @GetMapping("/unDistriCustlist")
    public AjaxResult unDistriCustlist(CustInfo custInfo) {

        Map<String, Object> resMap = new HashMap<String, Object>();
        try {
            Map<String, Object> paramsMap = custInfo.getParams();
            // 当前用户
            SysUser user = getLoginUser().getUser();

            SysDept dept = isysDeptService.selectDeptById(getLoginUser().getDeptId());

            custInfo.setStatus(StatusConstant.CUST_STATUS_UNALLOCATED);// 未指派
            paramsMap.put("cityName", dept.getCity());
            custInfo.setParams(paramsMap);

            startPage();
            List<CustInfo> list = custInfoService.selectCustInfoList2(custInfo);


            BaseSuborgConfig config = new BaseSuborgConfig();
            config.setOrgId(Long.valueOf(dept.getCompanyId()));
            List<BaseSuborgConfig> sysDictData = iBaseSuborgConfigService.selectBaseSuborgConfigList(config);

            if (sysDictData.isEmpty()) {
                resMap.put("distributeStatus", 0);
            } else {
                resMap.put("distributeStatus", sysDictData.get(0).getDistributeStatus());
            }
            resMap.put("list", getDataTable(list));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return AjaxResult.error("获取数据失败");
        }
        return AjaxResult.success(resMap);
    }

    /**
     * 城市待分配数据自动分配打开/关闭
     *
     * @return
     */
    @PostMapping("/updateDistributeSwitchStatus/{status}")
    public AjaxResult updateDistributeSwitchStatus(@PathVariable String status) {
        Map<String, Object> resMap = new HashMap<String, Object>();
        try {
            SysUser user = getLoginUser().getUser();

            SysDept sysDept = isysDeptService.selectDeptById(getLoginUser().getDeptId());


            if (!"2".equals(sysDept.getLevel()) && !"1".equals(sysDept.getLevel())) {
                return AjaxResult.error("无操作权限");
            }
            if (StringUtils.isBlank(status) || !"1,0".contains(status)) {
                return AjaxResult.error("入参有误");
            }
            BaseSuborgConfig orgConfig = new BaseSuborgConfig();
            orgConfig.setOrgId(Long.valueOf(sysDept.getCompanyId()));
            ;

            List<BaseSuborgConfig> baseSuborgConfig = iBaseSuborgConfigService.selectBaseSuborgConfigList(orgConfig);
            if (baseSuborgConfig.isEmpty()) {
                return AjaxResult.error("无操作权限");
            }
            orgConfig = baseSuborgConfig.get(0);
            orgConfig.setDistributeStatus(status);
            iBaseSuborgConfigService.updateBaseSuborgConfig(orgConfig);

            logger.info("城市[{}]-分公司[{}]待分配数据开关设置:操作人[{}]，设置标识[{}]", sysDept.getCity(), sysDept.getDeptId(), user.getUserId(), status);

        } catch (Exception e) {
            logger.error("城市待分配数据自动分配打开/关闭异常", e);
            return AjaxResult.error("操作异常");
        }
        return AjaxResult.success(status);
    }

    /**
     * 获取权限内的部门
     *
     * @return
     */
    @GetMapping("/getAllDept")
    public AjaxResult getAllDept() {
        return AjaxResult.success(isysDeptService.selectChildrenAllDeptById(getLoginUser().getDeptId()));

    }

    @GetMapping("/getAllDeptandUsers")
    public AjaxResult getAllDeptandUsers() {
        HashMap result = new HashMap();
        List<SysDept> sysDeptList = isysDeptService.selectChildrenAllDeptById(getLoginUser().getDeptId());
        Long[] orgIds = new Long[sysDeptList.size()];
        for (int i = 0; i < sysDeptList.size(); i++) {
            SysDept sysDept = sysDeptList.get(i);
            orgIds[i] = sysDept.getDeptId();
        }
        SysUser sysUser = new SysUser();
        Map<String, Object> sys_params = new HashMap<>();
        sys_params.put("orgIds", orgIds);
        sysUser.setParams(sys_params);

        List<SysUser> sysUsersList = userService.findAllUsersByOrgIdsAndEmpName(sysUser);
        result.put("sysDeptList", sysDeptList);
        result.put("sysUsersList", sysUsersList);
        return AjaxResult.success(result);

    }

    /**
     * 获取人员信息
     *
     * @return
     */
    @GetMapping("/queryUser")
    public AjaxResult queryUser(CustInfo custInfo) {
        //根据条件获取数据
        Map<String, Object> paramsMap = custInfo.getParams();
        SysUser userParams = new SysUser();
        Map<String, Object> resMap = new HashMap<String, Object>();

        try {
            SysUser user = getLoginUser().getUser();

            long orgId = MapUtils.getLong(paramsMap, "queryOrgList", -1L); // 部门
            String empName = MapUtils.getString(paramsMap, "empName"); //姓名
            String queryUserType = MapUtils.getString(paramsMap, "queryUserType"); //用户方式

            if (orgId == -1L) {
                orgId = user.getDeptId();
            }
            List<SysDept> sysDeptList = isysDeptService.selectChildrenAllDeptById(orgId);
            Long[] orgIds = new Long[sysDeptList.size()];
            for (int i = 0; i < sysDeptList.size(); i++) {
                SysDept sysDept = sysDeptList.get(i);
                orgIds[i] = sysDept.getDeptId();
            }
            paramsMap.put("orgIds", orgIds);
            paramsMap.put("empName", empName);

            List<SysUser> distrUserList = new ArrayList<SysUser>();

            if ("new".equals(queryUserType)) { // 可接收新数据的用户
                userParams.setParams(paramsMap);
                distrUserList = userService.findUsersRecNewByOrgIds(userParams);
            } else if ("public".equals(queryUserType)) { // 可接收公共池数据的用户
                distrUserList = userService.findUsersRecPublicByOrgIds(userParams);
            } else if ("selfRec".equals(queryUserType)) { // 打开了自助接收数据的用户
                paramsMap.put("isSelfRec", "1");
                userParams.setParams(paramsMap);
                distrUserList = userService.findUsersRecNewByOrgIds(userParams);
            } else { // 所有用户
                userParams.setParams(paramsMap);
                distrUserList = userService.findAllUsersByOrgIdsAndEmpName(userParams);
            }
            if (CollectionUtils.isNotEmpty(distrUserList)) {
                //List<FuncRole> userRoles = funcRoleService.findInRoleId(user.getRoleId());
                List<SysRole> roles = getLoginUser().getUser().getRoles();
                boolean filterSelf = true;
                for (SysRole role : roles) {
                    if (TypeConstant.ROLE_ID_3.equals(role.getRoleKey()) || TypeConstant.ROLE_ID_4.equals(role.getRoleKey()) || TypeConstant.ROLE_ID_5.equals(role.getRoleKey())) {
                        // 一级部长 和 二级部长可以分给自己20200115
                        filterSelf = false;
                        break;
                    }
                }
                if (filterSelf) {
                    // 非二级部长分配客户里面去除本人
                    final long userEmpId = user.getUserId();
                    distrUserList = distrUserList.stream().filter(item -> item.getUserId().longValue() != userEmpId).collect(Collectors.toList());
                }

//                for (SysUser sysUser : distrUserList) {
//                    List<SysRole> roleList2=  iroleService.selectRolesByUserId(sysUser.getUserId());
//
//                }

                // 过滤掉禁止接收数据分配的角色(20210927 add 过滤行政）

                distrUserList = distrUserList.stream().filter(item -> {
                    List<SysRole> roleList2 = iroleService.selectRolesByUserId(item.getUserId());
                    for (SysRole sysRole : roleList2) {
                        if (TypeConstant.ROLE_ID_3.equals(sysRole.getRoleKey()) ||
                                TypeConstant.ROLE_ID_4.equals(sysRole.getRoleKey()) ||
                                TypeConstant.ROLE_ID_40.equals(sysRole.getRoleKey()) ||
                                TypeConstant.ROLE_ID_5.equals(sysRole.getRoleKey()) ||
                                TypeConstant.ROLE_ID_8.equals(sysRole.getRoleKey())) {
                            return true;
                        }
                    }
                    return false;

                }).collect(Collectors.toList());
            }
            resMap.put("queryOrgList", sysDeptList);
            resMap.put("distrUserList", distrUserList);
        } catch (Exception e) {
            resMap.put("queryOrgList", new ArrayList<>());
            resMap.put("distrUserList", new ArrayList<>());
        }
        return AjaxResult.success(resMap);

    }

    /**
     * 新数据分配
     *
     * @return
     */
    @PostMapping("/newDataDistr/{custIds}/{empIds}")
    public AjaxResult newDataDistr(@PathVariable Long[] custIds, @PathVariable Long[] empIds) {
        Map<String, Object> resMap = new HashMap<String, Object>();
        try {
            if (custIds.length == 0 || empIds.length == 0) {
                return AjaxResult.error("待分配列表数据分配参数缺失");
            }
            String auto_distribute_flag = redisCache.getCacheObject(RedisConstant.AUTO_DISTRIBUTE_FLAG);

            logger.info("手动分配新数据判断自动任务分配标识：auto_distribute_flag = " + auto_distribute_flag);
            if (StringUtils.isBlank(auto_distribute_flag) || TypeConstant.FLAG_YES.equals(auto_distribute_flag)) {
                // 如果任务未执行或者已执行完毕，则可允许执行120分钟内不可重复执行
                int distri_time_interval = baseSysConfigService.getItemValueByItemKey(ConfigConstant.CUST_DATA_DISTRI_TIME_INTERVAL, 120);
                redisCache.setCacheObject(RedisConstant.AUTO_DISTRIBUTE_FLAG, TypeConstant.FLAG_NO, 60 * distri_time_interval, TimeUnit.SECONDS);
            } else {
                logger.info("自动任务分配尚未完成: 本次分配任务终止");
                return AjaxResult.error("自动任务分配正在进行，为避免重复分配，请2-3分钟后重试");
            }
            logger.info(String.format("待分配列表数据分配：客户ids[%s]，分配给顾问ids[%s]", custIds, empIds));
            SysUser currentUser = getLoginUser().getUser();
            CustInfo custInfo = new CustInfo();
            Map<String, Object> map_param = new HashMap<String, Object>();
            map_param.put("ids", custIds);
            custInfo.setParams(map_param);
            SysUser sysUser = new SysUser();

            // 待分配客户列表
            List<CustInfo> custlist = custInfoService.selectCustInfoList(custInfo);

            Map<String, Object> map_param2 = new HashMap<String, Object>();
            map_param2.put("empIds", empIds);
            sysUser.setParams(map_param2);

            // 待分配给顾问列表
            List<SysUser> userlist = userService.getByIds(sysUser);

            CollectionUtils.filter(userlist, new Predicate() {
                @Override
                public boolean evaluate(Object object) {
                    SysUser bsu = (SysUser) object;
                    return bsu.getReceiveTotal() < bsu.getReceiveTotallimit();
                }
            });
            // 开始分配
            List<CustInfo> allcustlist = new ArrayList<CustInfo>();
            int custSize = custlist.size();
            int userSize = userlist.size();
            for (int n = 0; n < userSize; n++) {
                int min = custSize * n / userSize;
                int max = custSize * (n + 1) / userSize;
                SysUser user = userlist.get(n);
                logger.info(String.format("用户[%s],分配数量[%s]", user.getUserId().intValue(), (max - min)));
                for (int i = min; i < max; i++) {
                    CustInfo cust = custlist.get(i);
                    cust.setDeptId(user.getDeptId());
                    cust.setUserId(user.getUserId());
                    cust.setStatus(StatusConstant.CUST_STATUS_UNACCEPT);
                    cust.setStarLevel("0");// 设置星级
                    cust.setReDistributeStatus(StatusConstant.DISTRIBUTE_STATUS_YES);// 直接分给顾问
                    //cust.setDistributeTime(new Date()); // 分配时间
                    cust.setOldDistributeTime(new Date());
                    StringBuffer distsb = new StringBuffer();
                    distsb.append(StringUtils.defaultIfBlank(cust.getDistributeRemark(), "")).append("<br>").append(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, new Date()))
                            .append(currentUser.getNickName()).append("初始分配给").append(user.getNickName()).append("-K-");
                    cust.setDistributeRemark(distsb.toString());
                    cust.setUpdateTime(new Date());
                    cust.setOldEmpId(user.getUserId());
                    cust.setOldUserId(user.getUserId());

                    custInfoService.updateCustInfo(cust);
                    allcustlist.add(cust);

                }
            }

            // 加密存储
            for (CustInfo info : allcustlist) {
                custInfoService.encryptMobile(info, logger);
            }
            // 发送短信给客户经理
            /*for (int i = 0; i < allcustlist.size(); i++) {
                custInfoService.sendNewDataSms(allcustlist.get(i));
            }*/
            logger.info(String.format("待分配列表数据分配完成：客户ids[%s]，分配给顾问ids[%s]", custIds, empIds));
            redisCache.setCacheObject(RedisConstant.AUTO_DISTRIBUTE_FLAG, TypeConstant.FLAG_YES);
        } catch (Exception e) {
            logger.error("待分配列表数据分配异常", e);
            redisCache.setCacheObject(RedisConstant.AUTO_DISTRIBUTE_FLAG, TypeConstant.FLAG_YES);
            return AjaxResult.error("待分配列表数据分配异常");
        }
        return AjaxResult.success("分配成功");
    }

    /**
     * 查询所有客户
     *
     * @return
     */
    @PreAuthorize("@ss.hasPermi('crmsys:allCustinfo:list')")
    @GetMapping("/allCustlist")
    public TableDataInfo allCustlist(CustInfo custInfo) {
        Map<String, Object> resMap = new HashMap<String, Object>();

        Map<String, Object> params = new HashMap<String, Object>();
        // 组装查询条件,必须有输入查询条件才查询结果
        resMap.put("list", new ArrayList());
        if (custInfo == null || (StringUtils.isBlank(custInfo.getCustName()) && StringUtils.isBlank(custInfo.getMobile()) && custInfo.getId() == null)) { // 默认不查询记录
            return getDataTable(new ArrayList());
        }

        SysUser user = getLoginUser().getUser();
        //long selectOrgId = getCurentCompanyOrgId(user.getOrgId());

        // 分公司总负责人级别以上能看整个城市，其他角色仅能看分公司级别
        Map<String, Object> roleMap = userInfoComm.getUserRoleCode();
        long selectOrgId = user.getDeptId();
        if (userInfoComm.isCompanyBoss(roleMap)) {
            selectOrgId = userInfoComm.getCurentCompanyOrgId(user.getDeptId());
        } else {
            selectOrgId = userInfoComm.getCurentSubCompanyOrgId(user.getDeptId());
        }
        List<SysDept> sysDepts = isysDeptService.selectChildrenAllDeptById(selectOrgId);
        Long[] orgIds = new Long[sysDepts.size()];
        for (int i = 0; i < sysDepts.size(); i++) {
            SysDept sysDept = sysDepts.get(i);
            orgIds[i] = sysDept.getDeptId();
        }
        Map<String, Object> custInfoParams = custInfo.getParams();

        if (!"".equals(custInfo.getCustName())) {
            custInfoParams.put("custNameEqual", custInfo.getCustName());
            custInfo.setCustName("");
        }
        custInfo.setDeptIds(orgIds);
        custInfoParams.put("isDelete", new int[]{0, 1, 2});
        custInfo.setParams(custInfoParams);

        startPage();
        List<CustInfo> list = custInfoService.selectCustInfoList(custInfo);
        return getDataTable(list);
    }

    /**
     * 查询团队客户
     *
     * @return
     */
    @PreAuthorize("@ss.hasPermi('crmsys:teamCustinfo:list')")
    @GetMapping("/teamCustlist")
    public AjaxResult teamCustlist(CustInfo custInfo) {
        Map<String, Object> resMap = new HashMap<String, Object>();
        Map<String, Object> params = custInfo.getParams();

        // team1-团队客户 team3-团队再分配客户 team2-团队必跟进客户
        String op = MapUtils.getString(params, "custOpType");
        // 20210330 增加团队客户客户所在库筛选
        String teamCustType = MapUtils.getString(params, "teamCustType");
        // 20210330 增加是否团队原始分配筛选
        String oriTeamDistributeFlag = MapUtils.getString(params, "oriTeamDistributeFlag");
        // 20210330 增加未跟进顾问筛选客户（例如筛选未跟进顾问为A和B，那筛选出来的客户列表就是A和B都没有跟进过的客户）
        Long[] notUpdateBys = (Long[]) MapUtils.getObject(params, "notUpdateBys");
        // 20230416 增加跟进过的顾问筛选客户（例如筛选跟进顾问为A和B，那筛选出来的客户列表就是A或者B跟进过的客户）
        Long[] updateBys = (Long[]) MapUtils.getObject(params, "updateBys");
        String off_day = MapUtils.getString(params, "off_day", "");
        String unfollow_day = MapUtils.getString(params, "unfollow_day", "");
        //是否原始分配
        String oriDistributeFlag = MapUtils.getString(params, "oriDistributeFlag", "");
        // 当前用户
        SysUser user = getLoginUser().getUser();
        // 通用部门、顾问、分配顾问查询条件组装
        long selectOrgId = custInfo.getOrgId() == null || custInfo.getOrgId() == -1L ? user.getDeptId() : custInfo.getOrgId();
        //查询值
        List<SysDept> deptList = isysDeptService.selectChildrenAllDeptById(selectOrgId);
        Map<String, Object> ids_map = userInfoComm.getDeptIdsEmpIdsByDepts(deptList);
//        Long[] deptIds = (Long[]) MapUtils.getObject(ids_map, "deptIds");
//        if (deptIds.length > 0) {
//            custInfo.setDeptIds(deptIds);
//        }
        Long[] empIds = (Long[]) MapUtils.getObject(ids_map, "empIds");
        if (empIds.length > 0) {
            custInfo.setUserIds(empIds);
        }
        custInfo.setIsDelete("0");
        String reDistributeStatus = "";
        if ("team3".equals(op) || "1".equals(teamCustType)) { // 团队再分配客户
            reDistributeStatus = StatusConstant.DISTRIBUTE_STATUS_RE;
        } else if ("team2".equals(op) || "2".equals(teamCustType)) { // 团队必跟进客户
            reDistributeStatus = StatusConstant.DISTRIBUTE_STATUS_MUST;
        } else if ("team1".equals(teamCustType)) { // 团队我的客户
            reDistributeStatus = StatusConstant.DISTRIBUTE_STATUS_YES;
        }

        custInfo.setReDistributeStatus(reDistributeStatus);


        if ("1".equals(oriTeamDistributeFlag)) {
            params.put("oriTeamDistY", 1);//是团队原始分配
        } else if ("2".equals(oriTeamDistributeFlag)) {
            params.put("oriTeamDistN", 1);//非团队原始分配
        }

        if (StringUtils.isNotBlank(off_day) && NumberUtils.isCreatable(off_day)) {
            // 通过未跟进超过几天查询的时候，查询结果集中剔除荐介客户
            params.put("starLevelNoEqual", TypeConstant.STAR_LEVEL_6);
        }
        if (StringUtils.isNotBlank(unfollow_day) && NumberUtils.isCreatable(unfollow_day)) {
            // 通过未跟进超过几天查询的时候，查询结果集中剔除荐介客户
            params.put("starLevelNoEqual", TypeConstant.STAR_LEVEL_6);
        }
        if (StringUtils.isNotBlank(custInfo.getFollowTimeStart())) {
            // 需要检索
            params.put("followTimeStart", custInfo.getFollowTimeStart());
        }
        if (StringUtils.isNotBlank(custInfo.getFollowTimeEnd())) {
            // 需要检索
            params.put("followTimeEnd", custInfo.getFollowTimeEnd());
        }
        custInfo.setParams(params);

        // 获取角色权限
        Map<String, Object> roleMap = userInfoComm.getUserRoleCode();
        // 计算数量
//        Map<String, Object> resMapCount = custInfoService.unfollowMorethandays("1", roleMap);
//        resMap.put("resMapCount", resMapCount);
        resMap.put("resMapCount", new HashMap<>());
        resMap.put("roleMap", roleMap);


        // 20200703若系统状态是3，则客户列表仅显示10（配置）天内的数据,且不包括扫码数据  目前不支持切换
//        if ("3".equals(user.getSysStatus())) {
//            int days = baseSysConfigService.getItemValueByItemKey(ConfigConstant.SYS_CUST_DATA_BEFORE_DAYS, 10);
//            params.put("applyTimeStart", DateUtil.format(DateUtil.addDay(new Date(), -days), DateUtil.DATE_TIME_FORMAT));
//            params.put("starLevelNoEqual", TypeConstant.STAR_LEVEL_6);
//        }
        custInfo.setOrgId(null);
        custInfo.setDeptId(null);

        if(custInfo.getUnfollow_day()!=null&&!"".equals(custInfo.getUnfollow_day())){
            Map<String,Object> map = custInfo.getParams();
            map.put("endupdateTime", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.addDays(new Date(), -Integer.parseInt(custInfo.getUnfollow_day()))));
            custInfo.setParams(map);
        }
        startPage();
        List<CustInfo> list = custInfoService.selectCustInfoList(custInfo);
        resMap.put("list", getDataTable(list));
        return AjaxResult.success(resMap);
    }

    /**
     * 离职人员客户
     *
     * @return
     */
    @PreAuthorize("@ss.hasPermi('crmsys:withdrawnCustinfo:list')")
    @GetMapping("/withdrawnCustlist")
    public AjaxResult withdrawnCustlist(CustInfo custInfo) {
        Map<String, Object> resMap = new HashMap<String, Object>();
        // 当前用户
        SysUser user = getLoginUser().getUser();
        Map<String, Object> params = custInfo.getParams();

        // 通用部门、顾问、分配顾问查询条件组装
        long selectOrgId = custInfo.getOrgId() == null || custInfo.getOrgId() == -1L ? user.getDeptId() : custInfo.getOrgId();

        List<SysDept> deptList = isysDeptService.selectChildrenAllDeptById(selectOrgId);
        Map<String, Object> ids_map = userInfoComm.getDeptIdsEmpIdsByDepts(deptList);
        Long[] deptIds = (Long[]) MapUtils.getObject(ids_map, "deptIds");
        if (deptIds.length > 0) {
            custInfo.setDeptIds(deptIds);
        }

        // 20211106 跟进次数区间查询处理
        if (StringUtils.isNotBlank(custInfo.getFollowTimeStart())) {
            // 需要检索
            params.put("followTimeStart", custInfo.getFollowTimeStart());
        }
        if (StringUtils.isNotBlank(custInfo.getFollowTimeEnd())) {
            // 需要检索
            params.put("followTimeEnd", custInfo.getFollowTimeEnd());
        }
        // 20211105 增加未跟进顾问筛选客户（例如筛选未跟进顾问为A和B，那筛选出来的客户列表就是A和B都没有跟进过的客户）

        params.put("withdrawn", "1"); // 标识区分离职
        custInfo.setIsDelete("0");//未加入垃圾库
        custInfo.setParams(params);

        custInfo.setDeptId(null);
        custInfo.setOrgId(null);
        startPage();
        List<CustInfo> list = custInfoService.selectCustInfoList(custInfo);
        resMap.put("list", getDataTable(list));

        return AjaxResult.success(resMap);
    }

    /**
     * 公共池/团队客户/离职客户数据分配
     *
     * @return
     */
    @PostMapping("/publicDataDistr/{custIds}/{empIds}/{withdrawn}")
    public AjaxResult publicDataDistr(@PathVariable Long[] custIds, @PathVariable Long[] empIds, @PathVariable String withdrawn) {
        Map<String, Object> resMap = new HashMap<String, Object>();
        try {
            SysUser user = getLoginUser().getUser();

            logger.info(String.format("公共池/团队客户/离职客户数据分配：客户ids[%s]，分配给顾问ids[%s]", custIds, empIds));


            //获取登录账号的角色信息
            Map<String, Object> roleMap = userInfoComm.getUserRoleCode();
            SysDept dept = isysDeptService.selectDeptById(getLoginUser().getDeptId());
            String company_id = dept.getCompanyId();
            // 待分配客户列表
            CustInfo custInfo = new CustInfo();
            Map<String, Object> map_param2 = new HashMap<String, Object>();
            map_param2.put("ids", custIds);
            map_param2.put("company_id", company_id);
            custInfo.setParams(map_param2);

            List<CustInfo> custlist = custInfoService.selectCustInfoList(custInfo);
            List<SysDept> deptList = isysDeptService.selectChildrenAllDeptById(user.getDeptId());
            Map<String, Object> ids_map = userInfoComm.getDeptIdsEmpIdsByDepts(deptList);

            // 获取当前操作人所在部门下的所有部门
            Long[] orgIdArr = (Long[]) MapUtils.getObject(ids_map, "deptIds");
            for (CustInfo info : custlist) {
                if (info.getDeptId() == null || !ArrayUtils.contains(orgIdArr, info.getDeptId())) {

                    return AjaxResult.error("客户ID[" + info.getId().longValue() + "]当前非本部门下不可操作");
                }
            }
            CollectionUtils.filter(custlist, new Predicate() {
                @Override
                public boolean evaluate(Object object) {
                    CustInfo info = (CustInfo) object;
                    // 非扫码和非锁定客户才允许分配 离职人员客户允许分配
                    return ((info.getLockFlag() == 0 || (info.getEmpId() != null && info.getEmpId().longValue() == user.getUserId().longValue()))
                            && !TypeConstant.STAR_LEVEL_6.equals(info.getStarLevel())
                            && (TypeConstant.FLAG_YES.equals(withdrawn) || !TypeConstant.CHL_QRCODE.equals(info.getChannelSource())));

                }
            });

            if (custlist.isEmpty()) {
                return AjaxResult.error("荐介客户、二维码客户和被锁定客户和其他指定客户不可操作");
            }

            SysUser sysUser = new SysUser();
            map_param2 = new HashMap<String, Object>();
            map_param2.put("empIds", empIds);
            sysUser.setParams(map_param2);
            // 待分配给顾问列表
            List<SysUser> userlist = userService.getByIds(sysUser);

            CollectionUtils.filter(userlist, new Predicate() {
                @Override
                public boolean evaluate(Object object) {
                    SysUser bsu = (SysUser) object;
                    return bsu.getReceiveTotal() < bsu.getReceiveTotallimit();
                }
            });
            List<Long> custIds2 = new ArrayList<>();

            for (CustInfo info : custlist) {
                custIds2.add(info.getId());
            }

            // 记录客户分配流水
            UserOperateRecord operate = new UserOperateRecord();
            Date createTime = new Date();
            operate.setCreateTime(createTime);
            operate.setEmpNo(user.getUserId().toString());
            operate.setEmpName(user.getNickName());
            operate.setOrgId(user.getDeptId());
            operate.setOperIds(Arrays.toString(custIds2.toArray()));
            operate.setOperNum(Long.valueOf(custlist.size()));
            operate.setStatus("0"); // 可撤销
            iuserOperateRecordService.insertUserOperateRecord(operate);

            // 开始分配
            int custSize = custlist.size();
            int userSize = userlist.size();
            for (int n = 0; n < userSize; n++) {
                int min = custSize * n / userSize;
                int max = custSize * (n + 1) / userSize;
                SysUser user2 = userlist.get(n);
                logger.info(String.format("用户[%s],分配数量[%s]", user2.getUserId().intValue(), (max - min)));
                for (int i = min; i < max; i++) {
                    CustInfo cust = custlist.get(i);
                    //20210519 修复数据分配后无法撤回的bug
                    UserOperateDetail userOperateDetail = new UserOperateDetail();
                    userOperateDetail.setOperId(operate.getId());
                    userOperateDetail.setCustId(cust.getId());
                    userOperateDetail.setEmpId(cust.getEmpId());
                    userOperateDetail.setOrgId(cust.getOrgId());
                    userOperateDetail.setReDistributeStatus(cust.getReDistributeStatus());
                    userOperateDetail.setDistrEmpId(user2.getUserId());
                    userOperateDetail.setDistrOrgId(user2.getUserId());
                    userOperateDetail.setCreateTime(createTime);
                    userOperateDetail.setOperEmpId(user.getUserId());
                    iuserOperateDetailService.insertUserOperateDetail(userOperateDetail);
                    cust.setDeptId(user2.getDeptId());
                    cust.setUserId(user2.getUserId());
                    cust.setReDistributeStatus(StatusConstant.DISTRIBUTE_STATUS_RE);// 再分配标识
                    cust.setReDistributeTime(new Date()); // 再分配时间
                    //cust.setDistributeTime(new Date());
                    cust.setIsDelete(TypeConstant.FLAG_NO);
                    StringBuffer distsb = new StringBuffer();
                    distsb.append(StringUtils.defaultIfBlank(cust.getDistributeRemark(), "")).append("<br>").append(
                                    DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, new Date()))
                            .append(user.getNickName()).append("分配给").append(user2.getNickName()).append("-K-");
                    cust.setDistributeRemark(distsb.toString());
                    cust.setUpdateTime(new Date());
                    cust.setLockFlag(0L);// 标识解锁
                    custInfoService.updateCustInfo(cust);
                }
            }
            // 批量更新
            logger.info(String.format("公共池/团队客户/离职客户数据分配完成：客户ids[%s]，分配给顾问ids[%s]", Arrays.toString(custIds), Arrays.toString(empIds)));

        } catch (Exception e) {
            logger.error("公共池/团队客户/离职客户数据分配异常", e);
            return AjaxResult.error("数据分配异常");
        }
        return AjaxResult.success("数据分配成功");
    }

    /**
     * 将客户移入删除历史库
     *
     * @return
     */
    @PostMapping("/batchRemoveToCustInfoDel/{ids}/{op}")
    public AjaxResult batchRemoveToCustInfoDel(@PathVariable Long[] ids, @PathVariable String op) {
        Map<String, Object> resMap = new HashMap<String, Object>();
        try {
            SysUser user = getLoginUser().getUser();
            SysDept dept = user.getDept();

            Map<String, Object> params = new HashMap<String, Object>();
            params.put("ids", ids);
            CustInfo custInfo = new CustInfo();
            custInfo.setParams(params);
            List<CustInfo> custInfos = custInfoService.selectCustInfoList(custInfo);

            List<CustBlackList> custBlackList = new ArrayList<>();
            if ("delete".equals(op)) {
                // 垃圾库彻底删除仅修改状态
                for (CustInfo info : custInfos) {
                    info.setIsDelete(TypeConstant.FLAG_YES_3);
                    info.setUpdateTime(new Date());
                    // 垃圾库彻底删除以后要加入黑名单
                    CustBlackList blackList2 = new CustBlackList();
                    blackList2.setMobile(info.getMobile());

                    if (!custBlackListService.selectCustBlackListList(blackList2).isEmpty()) {
                        continue;
                    }
                    String mobile = info.getMobile();
                    if (info.getMobile().contains("*")) {
                        AjaxResult ajaxResult = custInfoService.decryptMobile(info);
                        mobile = ajaxResult.get("msg").toString();
                    }

                    if (StringUtils.isNotBlank(mobile)) {
                        CustBlackList blackList = new CustBlackList();
                        blackList.setMobile(mobile);
                        blackList.setCreateTime(new Date());
                        blackList.setCreateBy(user.getUserId().toString());
                        custBlackListService.insertCustBlackList(blackList);
                    }
                    custInfoService.updateCustInfo(info);
                }
                logger.info("垃圾库彻底删除数量：" + custInfos.size());
            } else if (userInfoComm.isCompanyLeader(user)) {
                // 管理员彻底删除 才真正删除数据
                for (CustInfo info : custInfos) {
                    if (info.getStarLevel() != null && "1,9".contains(info.getStarLevel())) {
                        // 仅1星无用客户和搅扰客户可以删除
                        CustInfoDel del = new CustInfoDel();
                        ObjectUtil.copyProperties(info, del);
                        custInfoDelService.insertCustInfoDel(del);
                    }
                }
            }
            return AjaxResult.success("删除数据成功");
        } catch (Exception e) {
            logger.error("加入客户删除历史库操作异常", e);
            return AjaxResult.error("删除数据异常");
        }

    }

    /**
     * 查询垃圾池客户
     *
     * @return
     */
    @PreAuthorize("@ss.hasPermi('crmsys:deleteCustinfo:list')")
    @GetMapping("/deleteCustlist")
    public AjaxResult deleteCustlist(CustInfo custInfo) {
        Map<String, Object> resMap = new HashMap<String, Object>();
        // 当前用户
        SysUser user = getLoginUser().getUser();

        Map<String, Object> params = new HashMap<String, Object>();
        // 通用部门、顾问、分配顾问查询条件组装
        long selectOrgId = custInfo.getOrgId() == null || custInfo.getOrgId() == -1L ? user.getDeptId() : custInfo.getOrgId();
        List<SysDept> deptList = isysDeptService.selectChildrenAllDeptById(selectOrgId);
        Map<String, Object> ids_map = userInfoComm.getDeptIdsEmpIdsByDepts(deptList);
        Long[] deptIds = (Long[]) MapUtils.getObject(ids_map, "deptIds");
        if (deptIds.length > 0) {
            custInfo.setDeptIds(deptIds);
        }

//        custInfo.setUserIds((Long[]) MapUtils.getObject(ids_map, "empIds"));
        custInfo.setIsDelete("1");
        custInfo.setDeptId(null);
        custInfo.setOrgId(null);
        startPage();
        List<CustInfo> list = custInfoService.selectCustInfoList(custInfo);
        resMap.put("list", getDataTable(list));

        return AjaxResult.success(resMap);
    }

    /**
     * 查询垃圾中间库
     *
     * @return
     */
    @PreAuthorize("@ss.hasPermi('crmsys:deletingCustinfo:list')")
    @GetMapping("/deletingCustlist")
    public AjaxResult deletingCustlist(CustInfo custInfo) {
        Map<String, Object> resMap = new HashMap<String, Object>();
        // 当前用户
        SysUser user = getLoginUser().getUser();

        Map<String, Object> params = new HashMap<String, Object>();
        // 通用部门、顾问、分配顾问查询条件组装
        long selectOrgId = custInfo.getOrgId() == null || custInfo.getOrgId() == -1L ? user.getDeptId() : custInfo.getOrgId();
        List<SysDept> deptList = isysDeptService.selectChildrenAllDeptById(selectOrgId);
        Map<String, Object> ids_map = userInfoComm.getDeptIdsEmpIdsByDepts(deptList);
        Long[] deptIds = (Long[]) MapUtils.getObject(ids_map, "deptIds");
        if (deptIds.length > 0) {
            custInfo.setDeptIds(deptIds);
        }
        custInfo.setIsDelete("2");//垃圾中间库
        custInfo.setDeptId(null);
        custInfo.setOrgId(null);
        startPage();
        List<CustInfo> list = custInfoService.selectCustInfoList(custInfo);
        resMap.put("list", getDataTable(list));

        return AjaxResult.success(resMap);
    }

    /**
     * 垃圾中间库数据审核
     *
     * @return
     */
    @PostMapping("/deletingCustPass/{custId}")
    public AjaxResult deletingCustPass(@PathVariable Long custId) {
        CustInfo custInfo = custInfoService.selectCustInfoById(custId);
        if (custInfo == null) {
            return AjaxResult.error("客户信息不存在");
        }
        custInfo.setIsDelete(TypeConstant.FLAG_YES);// 加入垃圾正式库
        custInfoService.updateCustInfo(custInfo);
        return AjaxResult.success("加入垃圾库成功");
    }

    /**
     * 待点评客户：新数据产生的 3星、4星、5星客户待点评列表
     */
    @PreAuthorize("@ss.hasPermi('crmsys:custinfo:tobeReviewedCustlist')")
    @GetMapping("/tobeReviewedCustlist")
    public TableDataInfo tobeReviewedCustlist(CustInfo custInfo) {

        // 当前用户
        SysUser user = getLoginUser().getUser();
        Map<String, Object> params = custInfo.getParams();
        // 组装查询条件
        // 通用部门、顾问、分配顾问查询条件组装
        long selectOrgId = custInfo.getOrgId() == null || custInfo.getOrgId() == -1L ? user.getDeptId() : custInfo.getOrgId();

        List<SysDept> deptList = isysDeptService.selectChildrenAllDeptById(selectOrgId);
        Map<String, Object> ids_map = userInfoComm.getDeptIdsEmpIdsByDepts(deptList);
        Long[] deptIds = (Long[]) MapUtils.getObject(ids_map, "deptIds");
        if (deptIds.length > 0) {
            custInfo.setDeptIds(deptIds);
        }
        Long[] empIds = (Long[]) MapUtils.getObject(ids_map, "empIds");
        if (empIds.length > 0) {
            custInfo.setUserIds(empIds);
        }
        custInfo.setIsDelete("0");

        SysDept dept = isysDeptService.selectDeptById(getLoginUser().getDeptId());
        String company_id = dept.getCompanyId();

        params.put("starLevelIn", new long[]{3L, 4L, 5L, 7L});// 20201119将2星+加入列表中
        if ("1012".equals(company_id)) {
            // 20221012 南京系统2星+不进入待点评列表
            params.put("starLevelIn", new long[]{3L, 4L, 5L});
        }

        params.put("isNewData", "1");
        params.put("tobeReviewed", "1");
        custInfo.setParams(params);


        startPage();
        List<CustInfo> list = custInfoService.selectCustInfoList(custInfo);
        return getDataTable(list);
    }
    /**
     * 通用查询用户数据
     */
    @GetMapping("/getCustList")
    public TableDataInfo getCustList(CustInfo custInfo) {
        SysUser user = getLoginUser().getUser();
        long selectOrgId = custInfo.getOrgId() == null || custInfo.getOrgId() == -1L ? user.getDeptId() : custInfo.getOrgId();

        Map<String,Object> inparams=custInfo.getParams();
        Boolean isCheckDept=true;
        if("1".equals(MapUtils.getString(inparams,"isCheckDept","0") )){
            isCheckDept=false;
        }
        List<SysDept> deptList = isysDeptService.selectChildrenAllDeptById(selectOrgId);
        Map<String, Object> ids_map = userInfoComm.getDeptIdsEmpIdsByDepts(deptList);
        Long[] deptIds = (Long[]) MapUtils.getObject(ids_map, "deptIds");
        if(isCheckDept){
            custInfo.setDeptIds(deptIds);
        }
        String ids=MapUtils.getString(inparams,"ids","");
        if(!"".equals(ids))
        {
            String[] ids2=ids.split(",");
            Long[] ids3= new Long[ ids.length()];
            for (int i=0;i<ids2.length;i++) {
                ids3[i]=Long.valueOf( ids2[i]);
            }
            inparams.put("ids",ids3);
        }
        custInfo.setParams(inparams);
        startPage();
        List<CustInfo> list = custInfoService.selectCustInfoList(custInfo);
        return getDataTable(list);
    }
}
